package com.jwdf.uda.ui.activity.presenter;

import com.jwdf.uda.R;
import com.jwdf.uda.bean.PbBean;
import com.jwdf.uda.bean.UploadImage;
import com.jwdf.uda.event.GuideDetailEvent;
import com.jwdf.uda.http.AHttpService;
import com.jwdf.uda.http.HttpHelper;
import com.jwdf.uda.http.action.GuideAddInteractionAction;
import com.jwdf.uda.ui.activity.view.IGuideInteractionAddView;
import com.jwdf.uda.utils.EventBusUtil;
import com.jwdf.uda.utils.StringUtils;
import com.jwdf.uda.utils.ToastUtils;

import java.util.List;

import retrofit2.Response;

/**
 * 类说明：
 */
public class GuideInteractionAddPresenter extends AUploadImagePresenter<IGuideInteractionAddView> {
    private int mGuideId;

    public GuideInteractionAddPresenter(IGuideInteractionAddView iView, int guideId) {
        super(iView);
        mGuideId = guideId;
    }

    public void onHeadActionClick() {
        String content = mIView.getContent();
        List<UploadImage> uploadImages = getUploadImageList();
        if (StringUtils.isNullEmpty(content) && (uploadImages == null || uploadImages.size() <= 0)) {
            ToastUtils.show(getContext(), R.string.guide_interaction_add_hint);
            return;
        }
        mIView.getFragment().showProgressDialog();
        if(uploadImages != null && uploadImages.size() > 0){
            doUploadImagesAction();
        }else{
            doGuideInteractionAddAction(getImageTokenList());
        }
    }

    @Override
    protected List<UploadImage> getUploadImageList() {
        return mIView.getUploadImageList();
    }

    @Override
    protected void doUploadImage(UploadImage uploadImage) {
        mIView.setImageToken(uploadImage);
    }

    @Override
    protected void doUploadImagesSuccess(List<String> imageTokens) {
        doGuideInteractionAddAction(imageTokens);
    }

    public void doGuideInteractionAddAction(List<String> imageTokens) {
        GuideAddInteractionAction action = GuideAddInteractionAction.newInstance(getContext(), mGuideId, mIView.getContent(), imageTokens);
        mIView.getFragment().onNewRequestCall(action.request(new AHttpService.IResCallback<PbBean.PbResGuideAddInteraction>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResGuideAddInteraction> response, PbBean.PbBaseServerInfo baseServerInfo) {
                mIView.getFragment().closeProgressDialog();
                if (mIView.getFragment().getView() != null) {
                    if (HttpHelper.showError(getContext(), resultCode, baseServerInfo, R.string.error_operation)) {
                        return;
                    }

                    doGuideInteractionAddSuccess(response.body());
                }
            }
        }));
    }

    private void doGuideInteractionAddSuccess(PbBean.PbResGuideAddInteraction body) {
        mIView.getFragment().getActivity().finish();
        EventBusUtil.post(new GuideDetailEvent(GuideDetailEvent.EVENT_INTERACTION_ADD));
    }

}
